<template>
  <div class="container">
    <el-form inline>
      <el-form-item>
        <el-input placeholder="用户名" v-model="searchUser"></el-input>
      </el-form-item>
      <el-button class="el-icon-search" type="primary" @click="searchGetUser">查询</el-button>
      <el-button @click="clearSearch">清空</el-button>
    </el-form>

    <el-button type="primary" @click="addAclUser">添加</el-button>
    <el-button type="danger" @click="delManyUser" :disabled="!idList.length">
      批量删除
    </el-button>

    <el-table
      :data="aclUserList"
      v-loading="loading"
      @selection-change="handleSelectChange"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="username" label="用户名" width="80" />
      <el-table-column prop="nickName" label="用户昵称" width="80" />
      <el-table-column prop="roleName" label="权限列表" />
      <el-table-column prop="gmtCreate" label="创建时间" width="155" />
      <el-table-column prop="gmtModified" label="更新时间" width="155" />
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="{ row, $index }">
          <el-button
            type="info"
            size="mini"
            icon="el-icon-user-solid"
            title="分配角色"
            @click="showAssignRole(row)"
          />
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            title="修改用户"
            @click="showUpdateUser(row)"
          />
          <el-popconfirm
            :title="`确定删除 ${row.username} 吗?`"
            @onConfirm="removeUser(row.id)"
          >
            <el-button
              style="margin-left: 10px"
              slot="reference"
              type="danger"
              size="mini"
              icon="el-icon-delete"
              title="删除用户"
            />
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      style="padding: 20px 0"
      layout="prev, pager, next, jumper, ->,total,sizes"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
    />

    <!-- 添加用户 -->
    <el-dialog
      :title="user.id ? '修改用户' : '添加用户'"
      :visible.sync="dialogUserVisible"
    >
      <el-form
        ref="userForm"
        :model="user"
        :rules="userRules"
        label-width="120px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username" />
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="user.nickName" />
        </el-form-item>

        <el-form-item v-if="!user.id" label="用户密码" prop="password">
          <el-input v-model="user.password" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="addOrUpdate">
          确 定
        </el-button>
      </div>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog
      title="设置角色"
      :visible.sync="dialogRoleVisible"
      :before-close="resetRoleData"
    >
      <el-form>
        <el-form-item label="用户名">
          <el-input disabled :value="user.username"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group
            v-model="userRoleIds"
            @change="handleCheckedChange"
          >
            <el-checkbox
              v-for="role in allRoles"
              :label="role.id"
              :key="role.id"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button :loading="loading" type="primary" @click="assignRole">
          保存
        </el-button>
        <el-button @click="resetRoleData">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
export default {
  name: 'AclUserList',
  data() {
    return {
      loading: false,
      total: 0,
      limit: 5,
      page: 1,
      aclUserList: [{}], //用户列表
      dialogUserVisible: false,
      dialogRoleVisible: false, //显示设置角色对话框
      checkAll: false,
      isIndeterminate: true, //是否是不确定
      userRoleIds: [], //用户权限选择的列表
      allRoles: [], //所有的权限
      idList: [],
      searchUser:'',//用户收搜
      user: {
        username: '',
        nickname: '',
        password: ''
      },
      userRules: {
        // 用户添加/修改表单的校验规则
        username: [
          { required: true, message: '用户名必须输入', trigger: 'blur' },
          { min: 4, message: '用户名不能小于4位', trigger: 'blur' }
        ],
        password: [
          { required: true, validator: this.validatePassword, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getUsers()
  },
  methods: {
    // 显示指定角色的界面
    showAssignRole(row) {
      this.dialogRoleVisible = true
      this.user = row
      this.getRoles()
    },
    // 异步获取用户的角色列表
    async getRoles() {
      const res = await this.$API.aclUser.reqUserData(this.user.id)

      const { allRolesList, assignRoles } = res
      this.allRoles = allRolesList
      this.userRoleIds = assignRoles.map(item => item.id)
      this.checkAll = allRolesList.length === assignRoles.length
      this.isIndeterminate =
        assignRoles.length > 0 && assignRoles.length < allRolesList.length
    },
    // 设置权限
    async assignRole() {
      this.loading = true
      let { user, userRoleIds } = this
      const ids = userRoleIds.join(',') //数组转成字符串以","分开
      await this.$API.aclUser.reqDoAssign(user.id, ids)
      this.loading = false
      this.dialogRoleVisible = false
      this.$message.success('角色分配成功')
      //  重置表单
      this.resetRoleData()
      //  console.log(this.$store.getters.name,"this.$store.getters.name")
      // 如果是当前登录者，刷新页面
      if (this.$store.getters.name === user.username) {
        window.location.reload()
      }
    },

    // 修改用户
    showUpdateUser(row) {
      this.user = cloneDeep(row)
      this.dialogUserVisible = true
    },
    // 删除用户
    async removeUser(id) {
      await this.$API.aclUser.reqDeleteUser(id)
      // 页面数据也变
      await this.getUsers()
      this.$message.success('删除角色成功')
      //
    },
    // 批量删除
   delManyUser() {
      // console.log("this.idList",this.idList)
      this.$confirm('是否要删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
         await this.$API.aclUser.reqDeleteManyUser(this.idList)
          await this.getUsers()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })

    },
    // 添加管理用户
    addAclUser() {
      this.dialogUserVisible = true
      this.user = {}
    },
    // getUsers
    async getUsers() {
      this.loading = true
      let res = await this.$API.aclUser.reqAclUserList(this.page, this.limit)
      this.aclUserList = res.items
      // console.log(this.aclUserList,"this.aclUserList")
      this.total = res.total
      this.loading = false
    },

    handleSizeChange(val) {
      this.limit = val
      this.getUsers()
    },
    handlePageChange(val) {
      this.page = val
      this.getUsers()
    },
    // 自定义表单校验
    validatePassword(rule, value, callback) {
      if (!value) {
        callback('密码必须输入')
      } else if (!value || value.length < 6) {
        callback('密码不能小于6位')
      } else {
        callback()
      }
    },
    // 取消用户保存或是更新
    cancel() {
      this.dialogUserVisible = false
      this.user = {}
    },
    // 保存或是跟心用户
    addOrUpdate() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          const { user } = this

          this.loading = true

          this.$API.aclUser[user.id ? 'reqUpdateAclUser' : 'reqAddAclUser'](
            user
          ).then(result => {
            this.loading = false
            this.$message.success('保存成功!')
            this.getUsers(user.id ? this.page : 1)
            this.user = {}
            this.dialogUserVisible = false
          })
        }
      })
    },

    // 重置用户角色的数据
    resetRoleData() {
      this.dialogRoleVisible = false
      this.allRoles = []
      this.userRoleIds = []
      this.isIndeterminate = false
      this.checkAll = false
    },

    // 全选状态发生改变的监听
    handleCheckAllChange(val) {
      this.isIndeterminate = false
      // 如果全选时true/false
      // 如果当前全选, userRoleIds就是所有角色id的数组, 否则是空数组
      this.userRoleIds = val ? this.allRoles.map(item => item.id) : []
    },

    handleCheckedChange(value) {
      // this.userRoleIds=value
      // 判断如何全部都勾选了，这checkAll状态会改变
      const { userRoleIds, allRoles } = this
      this.checkAll =
        userRoleIds.length === allRoles.length && allRoles.length > 0
      this.isIndeterminate =
        userRoleIds.length > 0 && userRoleIds.length < allRoles.length
    },
    handleSelectChange(value) {
      console.log('value', value)
      this.idList = value.map(item => item.id)
    },
    // 清空搜索
    clearSearch(){
        this.searchUser=''
        this.getRoles()
    },
    searchGetUser(){}
  }
}
</script>

<style scoped>
.container {
  margin: 10px;
}
</style>
